/*
 * Copyright (c) 2017,安徽皖通科技股份有限公司 All rights reserved.
 */

package com.wttech.dzzf.process.service.fill;

import com.wtkj.vo.dzzf.base.kfwd.FundAccount;
import com.wttech.dzzf.process.dao.CbcBankDataCheckDao;
import com.wttech.dzzf.process.dao.FillMissingDataDao;
import com.wttech.dzzf.process.dao.TransferUserInfoDao;
import com.wttech.dzzf.process.service.base.BaseInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

import static com.wttech.dzzf.process.constant.UserConstants.DEFAULT_PROCESS_NUM;

/**
 * @author MaShibo
 * @date 2017/12/12.
 */
@Service
public class FillFundAccountInfoService {

	private static final Logger LOGGER = LoggerFactory.getLogger(FillFundAccountInfoService.class);

	@Resource
	private FillMissingDataDao fillMissingDataDao;

	@Resource
	private ThreadPoolTaskExecutor executor;

	@Resource
	private BaseInfoService baseInfoService;

	@Resource
	private TransferUserInfoDao transferUserInfoDao;

	@Resource
	private CbcBankDataCheckDao cbcBankDataCheckDao;


	private void process() {
		int total = fillMissingDataDao.queryTestFundAccountNum();
		LOGGER.info("共{}条资金账户信息待检测");
		int count = (int) Math.ceil((double) total / DEFAULT_PROCESS_NUM);
		LOGGER.info("共需要处理{}次", count);
		List<Future<Void>> futures = new ArrayList<>(count);
		for (int i = 0; i < count; i++) {
			int num = i + 1;
			futures.add(executor.submit(() -> {
				processOnce(num);
				return null;
			}));
		}
		baseInfoService.getFutureResult(futures);
		LOGGER.info("检测完成");
		executor.shutdown();
	}

	private void processOnce(int num) {
		LOGGER.info("第{}次开始执行", num);
		int startRow = (num - 1) * DEFAULT_PROCESS_NUM + 1;
		int endRow = num * DEFAULT_PROCESS_NUM;
		List<FundAccount> fundAccounts = cbcBankDataCheckDao.queryPageFundAccountInfos(startRow, endRow);
		fundAccounts.forEach(fundAccount -> {
			try {
				int count = fillMissingDataDao.queryFundAccountIdNum(fundAccount.getFundAccountId());
				if (count > 0) {
					return;
				}
				transferUserInfoDao.createDzzfObjcet(fundAccount);
			} catch (Exception e) {
				LOGGER.error(e.getMessage(), e);
			}
		});
		LOGGER.info("第{}次结束执行", num);
	}

	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		FillFundAccountInfoService service = context.getBean(FillFundAccountInfoService.class);
		service.process();
	}
}
